package com.uduemc.biso.module.basic.service.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.uduemc.biso.core.extities.center.MasterUser;
import com.uduemc.biso.module.basic.service.mapper.MasterUserMapper;
import com.uduemc.biso.module.basic.service.service.MasterUserService;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service
public class MasterUserServiceImpl implements MasterUserService {

	@Autowired
	private MasterUserMapper masterUserMapper;

	@Override
	public MasterUser insert(MasterUser masterUser) {
		masterUserMapper.insert(masterUser);
		return findOne(masterUser.getId());
	}

	@Override
	public MasterUser updateById(MasterUser masterUser) {
		masterUserMapper.updateByPrimaryKey(masterUser);
		return findOne(masterUser.getId());
	}

	@Override
	public MasterUser insertSelective(MasterUser masterUser) {
		masterUserMapper.insertSelective(masterUser);
		return findOne(masterUser.getId());
	}

	@Override
	public MasterUser updateByIdSelective(MasterUser masterUser) {
		masterUserMapper.updateByPrimaryKeySelective(masterUser);
		return findOne(masterUser.getId());
	}

	@Override
	public MasterUser findOne(Long id) {
		return masterUserMapper.selectByPrimaryKey(id);
	}

	@Override
	public int deleteById(Long id) {
		return masterUserMapper.deleteByPrimaryKey(id);
	}

	@Override
	public MasterUser findByUsername(String username) {
		Example example = new Example(MasterUser.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("username", username);
		return masterUserMapper.selectOneByExample(example);
	}

	@Override
	public MasterUser findByNumberKey(String numberKey) {
		Example example = new Example(MasterUser.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("numberKey", numberKey);
		return masterUserMapper.selectOneByExample(example);
	}

	@Override
	public String getCreateNumberKey() {
		long num = (long) ((Math.random() * 9 / 10) * Long.MAX_VALUE);
		String numberKey = String.valueOf(num);
		MasterUser findByNumberKey = findByNumberKey(numberKey);
		if (findByNumberKey == null) {
			return numberKey;
		}
		return getCreateNumberKey();
	}

}
